import { reactive, watch } from 'vue'

// 主题类型
export const THEME_TYPES = {
  DARK: 'dark',
  LIGHT: 'light'
}

// 深色主题配置
const darkTheme = {
  id: 'dark',
  name: '深色主题',
  colors: {
    // 背景颜色
    primary: '#0a0e1f',
    secondary: '#1a253d', 
    tertiary: '#243551',
    surface: 'rgba(26, 37, 61, 0.8)',
    
    // 文本颜色
    textPrimary: '#ffffff',
    textSecondary: 'rgba(255, 255, 255, 0.7)',
    textTertiary: 'rgba(255, 255, 255, 0.5)',
    
    // 强调色
    accent: '#00f5ff',
    accentHover: '#00d4dd',
    techBlue: '#0073e6',
    techBlueHover: '#005bb3',
    
    // 状态颜色
    success: '#22c55e',
    warning: '#f59e0b',
    error: '#ef4444',
    info: '#3b82f6',
    
    // 边框和分割线
    border: 'rgba(0, 245, 255, 0.2)',
    borderHover: 'rgba(0, 245, 255, 0.4)',
    divider: 'rgba(255, 255, 255, 0.1)',
    
    // 特殊效果
    glassBg: 'rgba(26, 37, 61, 0.8)',
    cardBg: 'linear-gradient(135deg, rgba(26, 37, 61, 0.8) 0%, rgba(36, 53, 81, 0.6) 100%)',
    navBg: 'rgba(10, 14, 31, 0.9)',
    shadow: 'rgba(0, 115, 230, 0.3)',
    glow: 'rgba(0, 245, 255, 0.3)'
  },
  gradients: {
    primary: 'linear-gradient(135deg, #0a0e1f 0%, #1a253d 50%, #243551 100%)',
    tech: 'linear-gradient(135deg, #0a0e1f 0%, #1f2d47 100%)',
    accent: 'linear-gradient(135deg, #0073e6 0%, #00f5ff 100%)',
    card: 'linear-gradient(135deg, rgba(26, 37, 61, 0.8) 0%, rgba(36, 53, 81, 0.6) 100%)'
  }
}

// 浅色主题配置
const lightTheme = {
  id: 'light',
  name: '浅色主题',
  colors: {
    // 背景颜色 - 真正的浅色背景
    primary: '#ffffff',
    secondary: '#f8fafc',
    tertiary: '#f1f5f9',
    surface: 'rgba(255, 255, 255, 0.95)',
    
    // 文本颜色 - 深色文本提供对比度
    textPrimary: '#1e293b',
    textSecondary: '#475569',
    textTertiary: '#64748b',
    
    // 强调色 - 保持科技蓝色但适配浅色背景
    accent: '#0073e6',
    accentHover: '#005bb3',
    techBlue: '#0073e6',
    techBlueHover: '#005bb3',
    
    // 状态颜色
    success: '#059669',
    warning: '#d97706',
    error: '#dc2626',
    info: '#0284c7',
    
    // 边框和分割线 - 浅色背景下的边框
    border: 'rgba(148, 163, 184, 0.3)',
    borderHover: 'rgba(148, 163, 184, 0.5)',
    divider: 'rgba(148, 163, 184, 0.2)',
    
    // 特殊效果 - 适配浅色背景
    glassBg: 'rgba(255, 255, 255, 0.9)',
    cardBg: 'linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.9) 100%)',
    navBg: 'rgba(255, 255, 255, 0.95)',
    shadow: 'rgba(0, 0, 0, 0.1)',
    glow: 'rgba(0, 115, 230, 0.15)'
  },
  gradients: {
    primary: 'linear-gradient(135deg, #ffffff 0%, #f8fafc 50%, #f1f5f9 100%)',
    tech: 'linear-gradient(135deg, #ffffff 0%, #f8fafc 100%)',
    accent: 'linear-gradient(135deg, #0073e6 0%, #1a8cff 100%)',
    card: 'linear-gradient(135deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.9) 100%)'
  }
}

// 主题配置映射
const themes = {
  [THEME_TYPES.DARK]: darkTheme,
  [THEME_TYPES.LIGHT]: lightTheme
}

// 全局主题状态
export const themeState = reactive({
  currentTheme: THEME_TYPES.DARK,
  theme: darkTheme,
  isLight: false,
  isDark: true
})

class ThemeService {
  constructor() {
    this.loadThemeFromStorage()
    this.applyTheme(themeState.currentTheme)
    
    // 监听主题变化，自动应用样式
    watch(() => themeState.currentTheme, (newTheme) => {
      this.applyTheme(newTheme)
    }, { immediate: true })
  }

  // 切换主题
  switchTheme(themeType) {
    if (themes[themeType]) {
      themeState.currentTheme = themeType
      themeState.theme = themes[themeType]
      themeState.isLight = themeType === THEME_TYPES.LIGHT
      themeState.isDark = themeType === THEME_TYPES.DARK
      
      this.saveThemeToStorage()
      this.applyTheme(themeType)
      
      console.log(`主题已切换到: ${themes[themeType].name}`)
      
      // 触发自定义事件，通知其他组件
      window.dispatchEvent(new CustomEvent('themeChange', {
        detail: { theme: themeType, themeConfig: themes[themeType] }
      }))
      
      return true
    }
    return false
  }

  // 切换到下一个主题
  toggleTheme() {
    const currentIndex = Object.values(THEME_TYPES).indexOf(themeState.currentTheme)
    const nextIndex = (currentIndex + 1) % Object.values(THEME_TYPES).length
    const nextTheme = Object.values(THEME_TYPES)[nextIndex]
    
    return this.switchTheme(nextTheme)
  }

  // 应用主题到DOM
  applyTheme(themeType) {
    const theme = themes[themeType]
    if (!theme) return

    const root = document.documentElement
    
    // 设置主题类名
    root.className = root.className.replace(/theme-\w+/g, '')
    root.classList.add(`theme-${themeType}`)
    
    // 设置CSS变量
    Object.entries(theme.colors).forEach(([key, value]) => {
      root.style.setProperty(`--color-${key}`, value)
    })
    
    Object.entries(theme.gradients).forEach(([key, value]) => {
      root.style.setProperty(`--gradient-${key}`, value)
    })
    
    // 设置body背景
    document.body.style.background = theme.gradients.primary
    document.body.style.color = theme.colors.textPrimary
    
    console.log(`应用主题: ${theme.name}`)
  }

  // 获取当前主题
  getCurrentTheme() {
    return themeState.currentTheme
  }

  // 获取当前主题配置
  getCurrentThemeConfig() {
    return themeState.theme
  }

  // 获取所有可用主题
  getAvailableThemes() {
    return Object.values(themes).map(theme => ({
      id: theme.id,
      name: theme.name
    }))
  }

  // 判断是否为深色主题
  isDarkTheme() {
    return themeState.isDark
  }

  // 判断是否为浅色主题
  isLightTheme() {
    return themeState.isLight
  }

  // 获取主题颜色
  getThemeColor(colorKey) {
    return themeState.theme.colors[colorKey] || ''
  }

  // 获取主题渐变
  getThemeGradient(gradientKey) {
    return themeState.theme.gradients[gradientKey] || ''
  }

  // 保存主题到本地存储
  saveThemeToStorage() {
    try {
      localStorage.setItem('currentTheme', themeState.currentTheme)
    } catch (error) {
      console.error('保存主题设置失败:', error)
    }
  }

  // 从本地存储加载主题
  loadThemeFromStorage() {
    try {
      const savedTheme = localStorage.getItem('currentTheme')
      if (savedTheme && themes[savedTheme]) {
        themeState.currentTheme = savedTheme
        themeState.theme = themes[savedTheme]
        themeState.isLight = savedTheme === THEME_TYPES.LIGHT
        themeState.isDark = savedTheme === THEME_TYPES.DARK
      }
    } catch (error) {
      console.error('加载主题设置失败:', error)
    }
  }

  // 注册主题变化监听器
  onThemeChange(callback) {
    const handler = (event) => {
      callback(event.detail)
    }
    
    window.addEventListener('themeChange', handler)
    
    // 返回取消监听的函数
    return () => {
      window.removeEventListener('themeChange', handler)
    }
  }

  // 获取主题适配的样式类
  getThemedClass(baseClass, variants = {}) {
    const currentTheme = themeState.currentTheme
    const themedClass = variants[currentTheme] || baseClass
    
    return `${baseClass} ${themedClass}`
  }

  // 检查系统偏好的主题
  detectSystemTheme() {
    if (window.matchMedia) {
      const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
      return isDarkMode ? THEME_TYPES.DARK : THEME_TYPES.LIGHT
    }
    return THEME_TYPES.DARK // 默认深色
  }

  // 自动跟随系统主题
  followSystemTheme() {
    const systemTheme = this.detectSystemTheme()
    this.switchTheme(systemTheme)
    
    // 监听系统主题变化
    if (window.matchMedia) {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      mediaQuery.addEventListener('change', (e) => {
        const newTheme = e.matches ? THEME_TYPES.DARK : THEME_TYPES.LIGHT
        this.switchTheme(newTheme)
      })
    }
  }
}

// 创建单例实例
export const themeService = new ThemeService()
export default themeService 